package cn.amaake.magicplugin.nacos.service;

import cn.amaake.magicplugin.nacos.config.NacosConfig;
import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.ssssssss.magicapi.core.model.MagicNotify;
import org.ssssssss.magicapi.core.service.MagicAPIService;

import java.util.concurrent.Executor;

public class NacosClusterListener {

    private final Logger logger = LoggerFactory.getLogger(NacosClusterListener.class);


    public NacosClusterListener(ConfigService configService,NacosConfig nacosConfig,MagicAPIService magicAPIService, ApplicationContext applicationContext,String instanceId)throws NacosException {

        Environment env = applicationContext.getEnvironment();
        String dataclusterid = env.getProperty("spring.application.name")+"-cluster";

        configService.addListener(dataclusterid, nacosConfig.getGroup(), new Listener() {
            @Override
            public void receiveConfigInfo(String configInfo) {

                MagicNotify magicNotify = JSONUtil.toBean(configInfo, MagicNotify.class);
                if(!magicNotify.getFrom().equals(instanceId)){
                    logger.info("当前实例ID："+instanceId+",收到修改配置:" + configInfo);
                    magicAPIService.processNotify(JSONUtil.toBean(configInfo, MagicNotify.class));
                }else{
                    logger.info("当前实例ID："+instanceId+",收到本机修改信息无需修改");
                }

            }
            @Override
            public Executor getExecutor() {
                return null;
            }
        });

    }





}
